﻿using System;
using System.Linq;
using LDSCore;
using LDSCore.Result;

namespace LDSModel.Dal
{
    public static class UserService
    {
        /// <summary>
        /// 当前用户信息
        /// </summary>
        public static Sys_User CurrentUser { get; private set; }

        public static OperationResult Login(string userName, string password)
        {
            var result = new OperationResult { Success = true };

            var context = new DatabaseEntities();
            var user = context.Sys_User.FirstOrDefault(u => u.UserName == userName);

            if (user == null)
            {
                result.Success = false;
                result.Code = ResultCode.ErrorUserName;
            }
            else
            {
                user = context.Sys_User.FirstOrDefault(u => u.UserName == userName && u.Password == password);

                if (user == null)
                {
                    result.Success = false;
                    result.Code = ResultCode.ErrorPassword;
                }
                else
                {
                    CurrentUser = Utils.Clone(user);

                    user.LastLoginTime = DateTime.Now;
                    LogService.Operation(OpType.Login, user.UserId, ResultCode.LoginSucess.ToMessage());
                    context.SaveChanges();
                }
            }

            return result;
        }

        public static OperationResult ModifyPwd(string userName, string password, string newPassword)
        {
            var result = new OperationResult { Success = true };

            var context = new DatabaseEntities();
            var user = context.Sys_User.FirstOrDefault(u => u.UserName == userName && u.Password == password);

            if (user == null)
            {
                result.Success = false;
                result.Code = ResultCode.ErrorPassword;
            }
            else
            {
                user.Password = newPassword;
                LogService.Operation(OpType.ModifyPwd, user.UserId, ResultCode.ModifyPwdSucess.ToMessage());
                context.SaveChanges();
            }

            return result;
        }

        public static OperationResult AddUser(string userName, string realName)
        {
            var result = new OperationResult { Success = true };

            var context = new DatabaseEntities();
            var user = context.Sys_User.FirstOrDefault(u => u.UserName == userName);

            if (user != null)
            {
                result.Success = false;
                result.Code = ResultCode.ExistUserName;
            }
            else
            {
                user = new Sys_User
                    {
                        UserId = Guid.NewGuid(),
                        UserName = userName,
                        RealName = realName,
                        Password = Utils.EncryptMd5("000000"),
                        IsManager = false
                    };
                user.LastLoginTime = user.CreateTime = DateTime.Now;
                context.AddToSys_User(user);
                LogService.Operation(OpType.UserManage, CurrentUser.UserId, string.Format(ResultCode.AddUserSucess.ToMessage(), userName));
                context.SaveChanges();
            }

            return result;
        }

        public static OperationResult ResetPwd(Guid userId)
        {
            var result = new OperationResult { Success = true };

            var context = new DatabaseEntities();

            var user = context.Sys_User.FirstOrDefault(u => u.UserId == userId);
            if (user != null)
            {
                user.Password = Utils.EncryptMd5("000000");
                LogService.Operation(OpType.UserManage, CurrentUser.UserId, string.Format(ResultCode.ResetPwdSucess.ToMessage(), user.UserName));
            }
            context.SaveChanges();

            return result;

        }

        public static OperationResult SetManager(Guid userId, bool isManager)
        {
            var result = new OperationResult { Success = true };

            var code = ResultCode.SetToManagerSuccess;
            if (!isManager) code = ResultCode.SetToUserSuccess;

            var context = new DatabaseEntities();

            var user = context.Sys_User.FirstOrDefault(u => u.UserId == userId);
            if (user != null)
            {
                user.IsManager = isManager;
                LogService.Operation(OpType.UserManage, CurrentUser.UserId, string.Format(code.ToMessage(), user.UserName));
            }
            context.SaveChanges();

            return result;
        }

        public static OperationResult Delete(Guid userId)
        {
            var result = new OperationResult { Success = true };

            var context = new DatabaseEntities();

            var user = context.Sys_User.FirstOrDefault(u => u.UserId == userId);
            context.Sys_User.DeleteObject(user);
            if (user != null)
                LogService.Operation(OpType.UserManage, CurrentUser.UserId, string.Format(ResultCode.DeleteUserSucess.ToMessage(), user.UserName));
            context.SaveChanges();

            return result;
        }

        public static IQueryable LoadUserList(string userName)
        {
            bool flag = string.IsNullOrWhiteSpace(userName);

            var context = new DatabaseEntities();

            IQueryable result = from u in context.Sys_User
                                where flag || (u.UserName.Contains(userName) || u.RealName.Contains(userName))
                                select new
                                {
                                    u.UserId,
                                    u.UserName,
                                    u.RealName,
                                    u.IsManager,
                                    u.CreateTime
                                };

            return result;
        }
    }
}
